Page({
  data: {
    walletData: {
      totalEarning: 0,
      nurseName: '',
      nurseId: ''
    }, // 钱包数据
    loading: true,  // 加载状态
    errorMsg: ''    // 错误提示信息
  },

  onLoad() {
    // 检查是否有本地用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      // 若没有用户信息，3秒后跳转到登录页
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login' // 假设登录页路径为/pages/login/login
        });
      }, 3000);
    }
    this.getWalletData();
  },

  // 页面显示时刷新数据
  onShow() {
    if (!this.data.loading) {
      this.setData({ loading: true });
      this.getWalletData();
    }
  },

  // 获取钱包数据（核心逻辑）
  getWalletData() {
    // 1. 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    console.log('本地用户信息：', userInfo);
    console.log('本地nurseId（类型）：', userInfo ? userInfo.nurseId : '无', typeof userInfo?.nurseId);
  
    if (!userInfo || !userInfo.nurseId) {
      this.setData({
        loading: false,
        errorMsg: '未获取到用户信息，请重新登录'
      });
      return;
    }
    const localNurseId = userInfo.nurseId;
  
    // 2. 调用后端接口
    wx.request({
      url: 'http://localhost:8080/orders/nurseping',
      method: 'GET',
      timeout: 10000,
      success: (res) => {
        console.log('接口返回原始数据：', res.data);
        if (res.data.code === 200) {
          const remoteDataList = res.data.data || [];
          console.log('后端返回的护士数据列表：', remoteDataList);
          
          // 提取后端nurseId及类型
          const remoteNurseIds = remoteDataList.map(item => ({
            id: item.nurseId,
            type: typeof item.nurseId
          }));
          console.log('后端nurseId列表（值+类型）：', remoteNurseIds);
  
          // 3. 匹配nurseId（统一转为字符串比较，避免类型问题）
          const matchedData = remoteDataList.find(
            item => String(item.nurseId) === String(localNurseId)
          );
  
          if (matchedData) {
            // 4. 格式化数据并更新视图
            this.setData({
              walletData: {
                totalEarning: (matchedData.totalEarning || 0).toFixed(2),
                nurseName: matchedData.nurseName || '未知护士',
                nurseId: matchedData.nurseId
              },
              errorMsg: ''
            });
          } else {
            // 未匹配到数据时显示0收入
            this.setData({
              errorMsg: '未找到对应钱包数据',
              walletData: {
                ...this.data.walletData,
                totalEarning: '0.00'
              }
            });
          }
        } else {
          this.setData({ errorMsg: '数据获取失败：' + (res.data.msg || '未知错误') });
        }
      },
      fail: (err) => {
        console.error('接口请求失败：', err);
        this.setData({ errorMsg: '网络请求失败，请检查网络或稍后重试' });
      },
      complete: () => {
        this.setData({ loading: false });
        // 3秒后自动隐藏错误提示
        if (this.data.errorMsg) {
          setTimeout(() => this.setData({ errorMsg: '' }), 3000);
        }
      }
    });
  },

  // 提现按钮点击事件
  withdraw() {
    const totalEarning = parseFloat(this.data.walletData.totalEarning) || 0;
    if (totalEarning <= 0) {
      wx.showToast({
        title: '暂无可用余额',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.showModal({
      title: '申请提现',
      content: `当前可提现金额：${this.data.walletData.totalEarning}元\n提现到账时间：1-3个工作日`,
      confirmText: '确认提现',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 调用提现接口示例
          wx.request({
            url: 'http://localhost:8080/wallet/withdraw',
            method: 'POST',
            data: {
              nurseId: this.data.walletData.nurseId,
              amount: totalEarning
            },
            success: (res) => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '提现申请已提交',
                  icon: 'success',
                  duration: 2000,
                  success: () => {
                    // 刷新数据
                    setTimeout(() => this.getWalletData(), 1000);
                  }
                });
              } else {
                wx.showToast({
                  title: res.data.msg || '提现失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络错误，提现失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 查看收支明细
  viewDetails() {
    wx.navigateTo({
      url: '/pages/earning-details/earning-details?nurseId=' + this.data.walletData.nurseId
    });
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '客服中心',
      content: '客服电话：400-123-4567\n工作时间：9:00-18:00',
      showCancel: false,
      confirmText: '拨打',
      success: (res) => {
        if (res.confirm) {
          // 调用拨打电话功能
          wx.makePhoneCall({
            phoneNumber: '4001234567'
          });
        }
      }
    });
  }
})